"""
命令发送API
"""
from typing import Optional, Dict, Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from .mqtt_publisher import get_command_publisher

router = APIRouter(prefix="/commands", tags=["commands"])


class CommandRequest(BaseModel):
    device_id: str
    command: str
    params: Optional[Dict[str, Any]] = None
    timeout: Optional[int] = None


class CommandResponse(BaseModel):
    success: bool
    command_id: str
    response: Optional[Dict[str, Any]] = None
    error: Optional[str] = None


@router.post("/send", response_model=CommandResponse)
async def send_command(request: CommandRequest):
    """发送命令到设备"""
    try:
        publisher = get_command_publisher()
        response = publisher.send_command(
            request.device_id,
            request.command,
            request.params,
            request.timeout
        )

        return CommandResponse(
            success=True,
            command_id=response.get("command_id"),
            response=response
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/send-async", response_model=CommandResponse)
async def send_command_async(request: CommandRequest):
    """异步发送命令到设备"""
    try:
        publisher = get_command_publisher()
        command_id = publisher.send_command_async(
            request.device_id,
            request.command,
            request.params
        )

        return CommandResponse(
            success=True,
            command_id=command_id
        )

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/history/{device_id}")
async def get_command_history(device_id: str, limit: int = 10):
    """获取设备命令历史"""
    # 实现从数据库查询命令历史
    pass
